package main

import (
	"encoding/base64"
	"fmt"
	"io"
	"log"
	"net/http"
	"strings"
)

// hello world, the web server
func MetricsServer(w http.ResponseWriter, req *http.Request) {
	var username, passwd string
	auth := req.Header.Get("Authorization")
	if auth == "" { //如果用户和密码不对重新弹出用户和密码输入框
		w.Header().Set("WWW-Authenticate", `Basic realm="Dotcoo User Login"`)
		w.WriteHeader(http.StatusUnauthorized)
		return
	}
	fmt.Println(auth)
	auths := strings.SplitN(auth, " ", 2)
	if len(auths) != 2 {
		fmt.Println("error")
		return
	}
	authMethod := auths[0]
	authB64 := auths[1]
	switch authMethod {
	case "Basic":
		authstr, err := base64.StdEncoding.DecodeString(authB64)
		if err != nil {
			fmt.Println(err)
			io.WriteString(w, "Unauthorized!\n")
			return
		}
		fmt.Println(string(authstr))
		userPwd := strings.SplitN(string(authstr), ":", 2)
		if len(userPwd) != 2 {
			fmt.Println("error")
			return
		}
		username = userPwd[0]
		passwd = userPwd[1]
		fmt.Println("Username:", username) //拿到username
		fmt.Println("Password:", passwd)   //拿到passwd
	default:
		fmt.Println("error")
		return
	}
	if username == "zyy" && passwd == "123" {
		io.WriteString(w, "#KKKKKKKKKKKKKKKKKKKK\n")
	} else { //如果用户和密码不对重新弹出用户和密码输入框
		w.Header().Set("WWW-Authenticate", `Basic realm="Dotcoo User Login"`)
		w.WriteHeader(http.StatusUnauthorized)
		return
	}
}
func main() {
	http.HandleFunc("/metrics", MetricsServer)
	err := http.ListenAndServe(":9100", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
